package capricornus.net.http
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;

	internal class HttpContinueRequest
	{
		/**
		 * 开头三个字节是长度 
		 */		
		public static const HEAD:int = 3;
		
		private var _id:int;
		private var _url:String;
		private var _callBackFun:Function;
		
		private var _urlStream:URLStream;
		
		public function HttpContinueRequest( id:int, url:String, callBackFun:Function )
		{
			_id = id;
			_url = url;
			_callBackFun = callBackFun;
			init();
		}
		
		private function init():void
		{
			_urlStream = new URLStream();
			_urlStream.addEventListener( ProgressEvent.PROGRESS, onProgress );
			_urlStream.addEventListener( IOErrorEvent.IO_ERROR, onError );
			_urlStream.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
			_urlStream.addEventListener( Event.COMPLETE, onComplete );
			
			_urlStream.load( new URLRequest( _url ) );
		}
		
		public function destroy():void
		{
			_urlStream.removeEventListener( ProgressEvent.PROGRESS, onProgress );
			_urlStream.removeEventListener( IOErrorEvent.IO_ERROR, onError );
			_urlStream.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
			_urlStream.removeEventListener( Event.COMPLETE, onComplete );
			
			try{ _urlStream.close(); } catch( e:Error ){};
		}
		
		private function onError( e:Event ):void
		{
			HttpRequestManager.clearContinue( _id );
		}
		
		private function onProgress( e:ProgressEvent ):void
		{
			handleData();
		}
		
		private var _head:int = -1;
		private function handleData():void
		{
			if( _head==-1 && _urlStream.bytesAvailable >= HEAD )
			{
				_head = int(_urlStream.readUTFBytes( HEAD ));
			}
			if( _head==-1 ) return;
			if( _urlStream.bytesAvailable >= _head )
			{
				var str:String = _urlStream.readUTFBytes( _head );
				_head = -1;
				if( _callBackFun != null )
				{
					_callBackFun( str );
				}
				handleData();
			}
		}
		
		private function onComplete( e:Event ):void
		{
			handleData();
			HttpRequestManager.clearContinue( _id );
		}
	}
}

















